export const goRmd = function () {
  document.querySelector('.home-main ').addEventListener("click", e => {
    const boxItem = e.target.closest('.box-item')
    if (boxItem) {
      // console.log(boxItem.dataset.id)
      this.userInfo.good_id = boxItem.dataset.id
      localStorage.setItem("userInfo", JSON.stringify(this.userInfo))

    }
  })
}

export const searchValue = function () {
  this.searchBtn.addEventListener("click", (e) => {
    e.preventDefault()

    // console.log(searchValue)
    if (this.userInfo.user_id && this.search.value) {
      sessionStorage.setItem("search_value", this.search.value)
      // 跳转到搜索页
      location.href = "../search/search.html"
    } else {
      alert("请先登录")
      return
    }
  })

  this.search.addEventListener("keydown", (e) => {
    // e.preventDefault()
    // 判断按下的键是否是回车键
    if (e.keyCode === 13) {
      if (this.userInfo.user_id && this.search.value) {
        sessionStorage.setItem("search_value", this.search.value)
        // 跳转到搜索页
        location.href = "../search/search.html"
      } else {
        console.log(1)
        alert("请先登录")
        return
      }
    }
  })
}

export const getDoms = function (obj) {
  let doms = {}
  // 获取对象中的key
  for (const key in obj) {
    const selector = obj[key]
    const element = document.querySelector(selector)
    doms[key] = element
  }
  return doms
}
// 封装渲染 函数  渲染 首页 数据  
export const render = function (data, str, className) {
  //  解构传入的数据
  let [a, b] = str
  // 模糊搜索 过滤
  let renderData = data.filter(item => item.category == a || item.category == a || item.title.includes(a) || item.category == b || item.category == b || item.title.includes(b))

  // 随机商品
  function getRandomElements (array, numElements) {
    const shuffledArray = array.sort(() => Math.random() - 0.5)
    return shuffledArray.slice(0, numElements)
  }

  renderData = getRandomElements(renderData, 10)
  // 选中  class
  const classItem = document.querySelector(`.${className}`)
  // 生成 商品数据
  let box_items = renderData.map(item => {
    return `
      <a class="box-item" href="../detail/hot_rmd.html"   data-id="${item.goods_id}" >
      ${item.is_hot ? '<div class="is_hot">热门</div>' : ""}
      ${item.is_sale ? `<div class="is_sale">${item.sale_type}</div>` : ""}
      <img src="" data-src ="${item.imgSmall_logo}"  class="lazyImg"  alt="">
      <div class="title">${item.title}</div> 
      <div class="current_price">¥${item.current_price} &nbsp;<span class="price">${item.price}</span> </div>
      </a>`
  })
  // console.log(box_items)
  classItem.innerHTML = box_items.join("")
}
//   渲染数据   模糊搜索    渲染对象
export const renderNav = function (data, str, name, num) {
  //  解构传入的数据
  let [a, b] = str
  // 模糊搜索 过滤
  let renderData = data.filter(item => item.category == a || item.category == a || item.title.includes(a) || item.category == b || item.category == b || item.title.includes(b))

  // 随机商品
  function getRandomElements (array, numElements) {
    const shuffledArray = array.sort(() => Math.random() - 0.5)
    return shuffledArray.slice(0, numElements)
  }
  renderData = getRandomElements(renderData, num)

  // 生成 商品数据
  let box_items = renderData.map(item => {
    return `
      <a class="box-item"  href="../detail/hot_rmd.html"    data-id="${item.goods_id}"  >
          <span class="is_hot">NEW</span>
          <img src="" data-src ="${item.imgSmall_logo}" class="lazyImg"  alt="">
          <div class="current_price">到手价¥<span>${item.current_price}</span></div>
        </a>`
  })

  name.innerHTML = box_items.join("")
}

export const goRmd1 = function (obj, info) {

  obj.addEventListener("click", e => {
    // e.preventDefault()
    const boxItem = e.target.closest('.box-item')
    if (boxItem) {
      info.good_id = boxItem.dataset.id
      localStorage.setItem("userInfo", JSON.stringify(info))
    }
  })
}

export const top = function () {
  let top = document.querySelector('.toTop')

  // 当用户滚动页面时显示或隐藏回到顶部按钮
  window.onscroll = function () {
    if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      top.style.display = "block"
    } else {
      top.style.display = "none"
    }
  }
  top.addEventListener('click', debounce(
    function () {
      document.documentElement.scrollTop = 0
      console.log(1)
    }, 200
  ))
}

// 封装防抖函数
export const debounce = function (func, delay) {
  let timerId
  return function (...args) {
    clearTimeout(timerId)

    timerId = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

// 封装节流函数
export const throttle = function (func, delay) {
  let timerId
  let lastTime = 0

  return function (...args) {
    const currentTime = Date.now()

    if (currentTime - lastTime >= delay) {
      func.apply(this, args)
      lastTime = currentTime
    } else {
      clearTimeout(timerId)

      timerId = setTimeout(() => {
        func.apply(this, args)
      }, delay)
    }
  }
}


//  图片懒加载
export const lazyImg = function () {

  // 获取页面所有图片
  let lazyImg = document.querySelectorAll(".lazyImg")
  // console.log(imgs)
  // 遍历所有图片 
  lazyImg.forEach(function (item) {
    // 判断是否进入可视区

    if (item.getBoundingClientRect().top <= window.innerHeight - 180) {

      item.src = item.dataset.src
      item.classList.remove('lazyImg')
    }
  })

}